from django.shortcuts import render
from django.views import View
from django.http import JsonResponse

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from meiduo_mall.utils.views import LoginRequiredMixin
from celery_tasks.email.tasks import send_verift_email
from users.models import User, Address
from django_redis import get_redis_connection
from django.contrib.auth import login, authenticate, logout
import json
import re
import logging
logger = logging.getLogger('django')

# Create your views here.


# 用户名检查
class UsernameCountView(View):

    def get(self, request, username):
        try:
            count = User.objects.filter(username=username).count()

        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '访问数据库错误',
            })

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'count': count,
        })


# 手机号检查
class MobileCountView(View):

    def get(self, request, mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return JsonResponse({'code': 404, 'errmsg': '访问数据库错误'})

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'count': count
        })


# 注册
class RegisterView(View):
    def post(self, request):
        # 提取json数据
        response_json = json.loads(request.body.decode())
        # print(response_json)

        # 分离json数据
        username = response_json.get('username')
        password = response_json.get('password')
        password2 = response_json.get('password2')
        mobile = response_json.get('mobile')
        sms_code = response_json.get('sms_code')
        allow = response_json.get('allow')

        # 判断数据是否完整
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 用户名验证
        if not re.match('^[a-zA-Z0-9_]{5,20}$', username):
            return JsonResponse({'code': 400, 'errmsg': 'username 格式错误'})

        # 密码验证
        if not re.match('^[a-zA-Z0-9_]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': 'password 格式错误'})

        # 确认密码验证
        if not password==password2:
            return JsonResponse({'code': 400, 'errmsg': '两次密码不一致'})

        # 手机号验证
        if not re.match('^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': 'mobile 格式错误'})

        # 连接redis数据库
        redis_conn = get_redis_connection('verify_code')

        # 短信验证码验证
        if not sms_code == redis_conn.get(f'sms_{mobile}').decode():
            return JsonResponse({'code': 400, 'errmsg': '验证码 错误'})

        # 用户协议验证
        if allow == False:
            return JsonResponse({'code': 400, 'errmsg': '用户协议 错误'})

        # 保存用户信息
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '保存到数据库失败'})

        # 实现状态保持
        login(request, user)

        # 设置返回参数
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 设置cookie
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        # 合并购物车
        response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        # 7.返回数据
        return response


# 登陆
class LoginView(View):
    def post(self, request):
        # 1.获取json数据
        response_json = json.loads(request.body.decode())

        # 2.提取数据
        username = response_json.get('username')
        password = response_json.get('password')
        remembered = response_json.get('remembered')

        # 3.检查参数完整性
        if not all([username, password]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 4.验证用户名密码
        user = authenticate(username=username, password=password)

        # 5.判断验证是否正确
        if not user:
            return JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})

        # 状态保持
        login(request, user)

        # 6.判断是否记住用户
        if remembered:
            # 记住 设置两周有效
            request.session.set_expiry(None)
        else:
            # 不记住 立刻失效
            request.session.set_expiry(0)

        # 设置返回参数
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 设置cookie
        response.set_cookie('username', user.username, max_age=3600*24*14)

        # 合并购物车
        response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        # 7.返回数据
        return response


# 登出
class LogoutView(View):
    def delete(self, request):
        # 清除session
        logout(request)

        # 构建相应对象
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        # 删除cookie
        response.delete_cookie('username')

        return response


# 用户中心
class UserInfoView(LoginRequiredMixin, View):
    def get(self, request):
        info_dict = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active,
        }
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'info_data': info_dict})


# 邮箱
class EmailView(View):
    # 添加邮箱
    def put(self, request):
        # 接收参数
        email = json.loads(request.body.decode()).get('email')

        # 校验参数
        if not email:
            return JsonResponse({'code': 400, 'errmsg': '缺少email参数'})

        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 保存邮箱数据
        try:
            user = request.user
            user.email = email
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '添加email出错'})

        # 发送邮箱验证码
        verify_url = request.user.generate_verify_email_url()

        send_verift_email.delay(email, verify_url)

        # 添加成功
        return JsonResponse({'code': 0, 'errmsg': 'ok'})


# 验证邮箱
class VerifyEmailView(View):

    def put(self, request):
        # 提取数据
        token = request.GET.get('token')

        # 检测数据
        if not token:
            return JsonResponse({'code': 400, 'errmsg': '缺少token'})

        user = User.check_verify_email_token(token)

        # 验证
        if not user:
            return JsonResponse({'code': 400, 'errmsg': 'token失效'})

        # 修改邮件验证状态
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '激活邮件失败'})

        return JsonResponse({'code': 0, 'errmsg': 'ok'})


# class CreateAddressView(View):
#     def post(self, request):
#         # 获取地址个数:
#         try:
#             count = Address.objects.filter(user=request.user, is_deleted=False).count()
#         except Exception as e:
#             return JsonResponse({'code': 400, 'errmsg': '获取地址数据出错'})
#
#         # 判断是否超过地址上限：最多20个
#         if count >= 20:
#             return JsonResponse({'code': 400, 'errmsg': '超过地址数量上限'})
#
#         json_dict = json.loads(request.body.decode())
#         receiver = json_dict.get('receiver')
#         province_id = json_dict.get('province_id')
#         city_id = json_dict.get('city_id')
#         district_id = json_dict.get('district_id')
#         place = json_dict.get('place')
#         mobile = json_dict.get('mobile')
#         tel = json_dict.get('tel')
#         email = json_dict.get('email')
#
#         # 校验参数
#         if not all([receiver, province_id, city_id, district_id, place, mobile]):
#             return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
#
#         if not re.match(r'^1[3-9]\d{9}$', mobile):
#             return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
#
#         if tel:
#             if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
#                 return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
#
#         if email:
#             if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
#                 return JsonResponse({'code': 400, 'errmsg': '参数email有误'})
#
#         # 保存地址信息
#         try:
#
#             address = Address.objects.create(
#                 user=request.user,
#                 title=receiver,
#                 receiver=receiver,
#                 province_id=province_id,
#                 city_id=city_id,
#                 district_id=district_id,
#                 place=place,
#                 mobile=mobile,
#                 tel=tel,
#                 email=email
#             )
#
#             # 设置默认地址
#             if not request.user.default_address:
#                 request.user.default_address = address
#                 request.user.save()
#
#         except Exception as e:
#             logger.error(e)
#             return JsonResponse({'code': 400, 'errmsg': '新增地址失败'})
#
#         # 构建响应
#         address_dict = {
#             'id': address.id,
#             'receiver': address.receiver,
#             'province': address.province,
#             'city': address.city,
#             'district': address.district,
#             'place': address.place,
#             'mobile': address.mobile,
#             'tel': address.tel,
#             'email': address.email
#         }
#
#         return JsonResponse({'code': 0, 'errmsg': '新增地址成功', 'address': address_dict})

class CreateAddressView(View):
    """新增地址"""

    def post(self, request):
        """实现新增地址逻辑"""

        # 获取地址个数:
        try:
           count = Address.objects.filter(user=request.user,
                                       is_deleted=False).count()
        except Exception as e:
            return JsonResponse({'code': 400,
                                      'errmsg': '获取地址数据出错'})
        # 判断是否超过地址上限：最多20个
        if count >= 20:
            return JsonResponse({'code': 400,
                                      'errmsg': '超过地址数量上限'})

        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})


        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title = receiver,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )

            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '新增地址失败'})

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return JsonResponse({'code': 0,
                                  'errmsg': '新增地址成功',
                                  'address':address_dict})


class AddressView(View):
    def get(self, request):
        addresses = Address.objects.filter(user=request.user, is_deleted=False)

        address_dict_list = []
        for address in addresses:
            address_dict = {
                'id': address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            default_address = request.user.default_address

            if address.id == default_address.id:
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': address_dict_list,
                             'default_address_id': default_id})


class UpdateDestroyAddressView(View):
    def put(self, request, address_id):

        # 接收参数
        json_dict = json.loads(request.body.decode())

        # 分离参数
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})

    def delete(self, request, address_id):

        try:
            address = Address.objects.get(id=address_id)

            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '删除地址失败'})

        return JsonResponse({'code': 0, 'errmsg': '删除地址成功'})


class DefaultAddressView(View):

    def put(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id)

            user = request.user

            user.default_address = address
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '设置默认地址失败'})

        return JsonResponse({'code': 0, 'errmsg': 'ok'})


class UpdateTitleAddressView(View):
    def put(self, request, address_id):
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '设置地址标题失败'})

        return JsonResponse({'code': 0, 'errmsg': 'ok'})


class ChangePasswordView(LoginRequiredMixin, View):
    def put(self, request):

        json_dict = json.loads(request.body.decode())

        old_password = json_dict.get('old_password')
        new_password = json_dict.get('new_password')
        new_password2 = json_dict.get('new_password2')

        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({'code': 400, 'errmsg': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400, 'errmsg': '密码最少8位,最长20位'})

        if not new_password == new_password2:
            return JsonResponse({'code': 400, 'errmsg': '两次输入密码不一致'})

        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '修改密码失败'})

        logout(request)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.delete_cookie('username')

        return response


class UserBrowseHistory(LoginRequiredMixin, View):
    def post(self, request):
        # 接收参数
        sku_id = json.loads(request.body.decode()).get('sku_id')

        # 校验参数:
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': 'sku不存在'})

        # 保存用户浏览数据
        redis_conn = get_redis_connection('history')

        pl = redis_conn.pipeline()
        user_id = request.user.id

        # 先去重: 这里给 0 代表去除所有的 sku_id
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 再存储
        pl.lpush('history_%s' % user_id, sku_id)
        # 最后截取: 界面有限, 只保留 5 个
        pl.ltrim('history_%s' % user_id, 0, 4)
        # 执行管道
        pl.execute()

        return JsonResponse({'code': 0, 'errmsg': 'ok'})

    def get(self, request):
        # 获取Redis存储的sku_id列表信息
        redis_conn = get_redis_connection('history')
        # 获取当前用户所有的浏览记录
        sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)

        # 根据sku_ids列表数据，查询出商品sku信息
        skus = []

        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image_url,
                'price': sku.price,
            })

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'skus': skus})




